package dymnd.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Enumeration;
import java.util.Hashtable;


public final class ConfigHashtable {
    private Hashtable<String,String> entries = new Hashtable<String,String>();
    private File file;
    
    public ConfigHashtable(){
        StackTraceElement[] a = Thread.currentThread().getStackTrace();
        if(new File("configs").exists()==false)new File("configs").mkdirs();
        
        String location = "configs/"+a[2].getClassName()+".config.hash";
        file = new File(location);
        load();
    }
    public ConfigHashtable(String name){
        StackTraceElement[] a = Thread.currentThread().getStackTrace();
        if(new File("configs").exists()==false)new File("configs").mkdirs();
        
        String location = "configs/"+a[2].getClassName()+".config.hash";
        if(name.length()!=0) location+="."+name;
        file = new File(location);
            load();
    }
    
    private void load(){
        try {
            if(!file.exists())return;
            FileInputStream fis = new FileInputStream(file);
            int ch = 0;
            while((ch = fis.read())!=-1){
                int length = ch*256;
                ch = fis.read();
                length += ch;
                String buffer = "";
                while(length-->0 && (ch=fis.read())!=-1 )buffer+=(char)ch;
                String[] parts = buffer.split(""+(char)0);
                entries.put(parts[0],parts[1]);
            }
            fis.close();
        } catch (Exception ex) {
        }
    }
    private void save(){
       
    	try {
            FileOutputStream fos = new FileOutputStream(file);
            Enumeration<String> keys = entries.keys();
            while(keys.hasMoreElements()){
            	String key = keys.nextElement();
                String entry = entries.get(key);
                int length = entry.length()+key.length()+1;
                fos.write(length/256);
                fos.write(length%256);
                fos.write(key.getBytes());
                fos.write(0);
                fos.write(entry.getBytes());
            }
            fos.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public int size(){
        return entries.size();
    }
    public String get(String key){
        String s = null;
        try	{
        	s = entries.get(key);
       
        }	catch(NullPointerException x)	{
        	s = "null";
        }
        return s;
    	
    }
    public void set(String key,String value){
        entries.put(key, value);
        save();
    }
    public void remove(String key){
        entries.remove(key);
        save();
    }
    public String[] getKeys(){
    	return entries.keySet().toArray(new String[0]);
    }
}
